using System;
using System.Reflection;
using System.Reflection.Emit;

namespace Dida.Dxml
{
	internal static class SerializationAssembly
	{
		static AssemblyBuilder asmBuilder;
		static ModuleBuilder moduleBuilder;

		static TypeBuilder globalsType = null;
		static int nextGlobalMethodIndex = 0;

		static SerializationAssembly()
		{
			AppDomain domain = AppDomain.CurrentDomain;
			asmBuilder = domain.DefineDynamicAssembly(
				new System.Reflection.AssemblyName("SerializationAssembly"),
				AssemblyBuilderAccess.Run);

			moduleBuilder = asmBuilder.DefineDynamicModule("tehModule");

			globalsType = moduleBuilder.DefineType("__globals",TypeAttributes.Public);
		}

		public static TypeBuilder CreateType(string name)
		{
			return moduleBuilder.DefineType(name);
		}

		public static MethodBuilder DefineGlobalMethod(Type returnType,Type[] paramTypes)
		{
			string name;
			//do
			//{
				name = "globalMethod_" + nextGlobalMethodIndex.ToString();
				nextGlobalMethodIndex++;
			//}
			//while (globalsType.GetMethod(name) != null*/);

			return globalsType.DefineMethod(name, MethodAttributes.Static |
				MethodAttributes.Public,returnType,paramTypes);
		}

		public static void Finish()
		{
			globalsType.CreateType();
		}
	}
}